import request from '@/api/api'
import * as type from '../mutationTypes'
import commonUtils from '@/assets/commonUtil'

const state = {
  listData: [],
  modifyId: ''
}

const mutations = {
  // 修改列表数据状态
  [type.LIST_DATA] (state, dataModel) {
    state.listData = dataModel
  },
  // 获取需要修改数据的id
  [type.MODIFY_ID] (state, id) {
    state.modifyId = id
  }
}

const actions = {
  // 获取日志列表数据
  initPage: function ({ commit }) {
    request.journalList()
      .then(res => {
        commit(type.LIST_DATA, res.data)
      })
  },
  // 新增日志
  addJournal: function ({ dispatch, commit }, addModel) {
    request.addJournal(addModel)
      .then(res => {
        if (res.data.updatedExisting === true) {
          commonUtils.setMessage('success', '新增成功')
          // 新增成功后，dispatch分发重新拉取一下列表数据
          dispatch('initPage')
        } else {
          commonUtils.setMessage('warnning', '新增失败')
        }
      })
  },
  // 改变修改数据的id
  modifyIdData: function ({ commit }, id) {
    commit(type.MODIFY_ID, id)
  },
  // 修改指定id的数据model
  modifyJournal: function ({ dispatch, commit }, model) {
    // 请求修改的接口
    request.modifyJournal(state.modifyId, model)
      .then(res => {
        if (res.data.updatedExisting === true) {
          commonUtils.setMessage('success', '修改成功')
          // 修改成功后，dispatch分发重新拉取一下列表数据
          dispatch('initPage')
        } else {
          commonUtils.setMessage('warnning', '修改失败')
        }
      })
  },
  // 删除
  deleteJournal: function ({ dispatch, commit }, id) {
    request.deleteJournal(id)
      .then(res => {
        if (res.data.ok === 1) {
          commonUtils.setMessage('success', '删除成功')
          // 修改成功后，dispatch分发重新拉取一下列表数据
          dispatch('initPage')
        } else {
          commonUtils.setMessage('warning', '删除失败')
        }
      })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
